import 'package:aio/aio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/http/bean/wroks/contract_bean.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/works/public/items/ui_base.dart';
import 'package:app/src/ui/route/works/public/items/ui_card.dart';

import '../../../../../http/bean/works_2023/contractroyaltyrateapplycheck_bean.dart';
import '../../../../../http/model/user_model.dart';
import '../../../../app_ui.dart';

///修改提成比例审核
class UiContractRoyaltyRateApplyCheckUpdate {
  ///data 信息
  ///oldData 历史信息
  static Widget build(
      BuildContext context,
      ModifyContractRoyaltyRateBean? data,
      ModifyContractRoyaltyRateBean? oldData,
      ContractRoyaltyRateApplyCheckBean? checkBean,
      {String? title}) {
    return StatefulBuilder(builder: (context, setState) {
      _setState = setState;
      List<Widget> children = [];
      if (StringUtils.isEmpty(title)) {
        title = AppStrings.of(context).Modifycommission; //修改提成比例
      }
      children.add(UiBase.title(context, title)); //标题
      bool readOnly = false;
      if (data?.MerchandiserRoyalty != null &&
          data!.MerchandiserRoyalty!.length >= 2) {
        readOnly = true;
      }
      children.add(UiBase.itemWithEdit(
          context,
          AppStrings.of(context).MerchandiserRoyaltyRateApply,
          data?.getSalesmanRoyaltyRateApply(),
          oldData?.SalesmanRoyaltyRateApply,
          isChangeColor: false,
          isNegative: false,
          isEmpty: true,
          unit: "%",
          readOnly: readOnly,
          isDecimal: true, onChanged: (value) {
        if (StringUtils.isEmpty(value)) {
          data?.SalesmanRoyaltyRateApply = "0"; //不能为空，为空，提交接口会报数据格式错误。
        } else {
          data?.SalesmanRoyaltyRateApply = value;
        }
      },
          focusNode: FocusNodeManager.getFocusNode(
                  "$AppStrings.of(context).MerchandiserRoyaltyRateApply")
              .addListener((value) {
            if (!value) {
              //失去焦点;页面刷新。
              _setState?.call(() {
                if (data?.MerchandiserRoyalty == null ||
                    data!.MerchandiserRoyalty!.length <= 0) {
                  data?.MerchandiserRoyalty = [];
                  var mDatas = data?.MerchandiserRoyalty;
                  //新增一个
                  if (StringUtils.isEmpty(checkBean?.SalesmanId)) {
                    UserModel.getManagergetlistWith02(context, true, (value) {
                      if (value.isSuccessForData()) {
                        if (value.Data != null && value.Data!.length > 0) {
                          var data = value.Data![0];
                          _setState?.call(() {
                            var bean = MerchandiserRoyaltyBaen();
                            bean.PersonId = data.PersonId; //fixme 需要接口返回，业务员的id
                            bean.PersonName = data?.PersonName;
                            bean.ContractCode = checkBean?.ContractCode;
                            bean.Ratio = checkBean?.ModifyContractRoyaltyRate
                                    ?.SalesmanRoyaltyRateApply ??
                                "0";
                            mDatas?.add(bean);
                          });
                        }
                      }
                    });
                  } else {
                    var bean = MerchandiserRoyaltyBaen();
                    bean.PersonId = checkBean?.SalesmanId; //fixme 需要接口返回，业务员的id
                    bean.PersonName = checkBean?.SalesmanName;
                    bean.ContractCode = data?.ContractCode;
                    bean.Ratio = data?.SalesmanRoyaltyRateApply ?? "0";
                    mDatas?.add(bean);
                  }
                } else if (data?.SalesmanRoyaltyRateApply != null &&
                    //刷新数据
                    data!.MerchandiserRoyalty!.length == 1) {
                  data!.MerchandiserRoyalty![0].Ratio =
                      data?.SalesmanRoyaltyRateApply ?? "";
                }
              });
            }
          }))); //总业务提成
      children.add(UiBase.itemWithEdit(
          context,
          AppStrings.of(context).Customerservicecommission,
          data?.MerchandiserRoyaltyRateApply,
          oldData?.MerchandiserRoyaltyRateApply,
          isChangeColor: false,
          isEmpty: true,
          isNegative: false,
          unit: "%",
          isDecimal: true, onChanged: (value) {
        if (StringUtils.isEmpty(value)) {
          data?.MerchandiserRoyaltyRateApply = "0"; //不能为空，为空，提交接口会报数据格式错误。
        } else {
          data?.MerchandiserRoyaltyRateApply = value;
        }
      })); //客服提成
      var Newbusinesscommission = _materialButton(
          AppStrings.of(context).Newbusinesscommission, onPressed: () {
        UserModel.getManagergetlistWith02(context, true, (value) {
          if (value.isSuccessForCode()) {
            var datas = <RollerBean>[];
            value?.Data?.forEach((element) {
              datas.add(
                  RollerBean(key: element.PersonId, value: element.PersonName));
            });
            var mDatas = data?.MerchandiserRoyalty;
            AppDialog.showDialogWithRollerPicker(context,
                    datas: datas, value: null)
                ?.then((value) {
              if (value != null && value!.value != null) {
                MerchandiserRoyaltyBaen? delData = null;
                mDatas?.forEach((element) {
                  if (element.PersonId == value.key) {
                    delData = element;
                  }
                });
                if (delData != null) {
                  mDatas?.remove(delData); //移除掉重复的。(把之前旧的移除掉，以现在最新的为准)
                }
                _setState?.call(() {
                  var bean = MerchandiserRoyaltyBaen();
                  if (delData != null) {
                    bean.Ratio = delData?.Ratio ?? "0";
                  } else {
                    bean.Ratio = "0";
                  }
                  bean.PersonId = value.key;
                  bean.PersonName = value.value;
                  bean.ContractCode = data?.ContractCode;
                  mDatas?.add(bean);
                });
              }
            });
          } else {
            AppDialog.showDialogWithInfo(context, content: value?.MsgDetail);
          }
        });
      }); //新增业务提成
      children.add(Newbusinesscommission);
      children.add(SizedBox(
        height: 16,
      ));
      children.add(_table(context, data));
      var column = UiBase.column(context, children);
      var card = UiCard.build(context, column);
      return card;
    });
  }

  ///fixme Table表格里的行TabRow;每一行的表格数量必须相等。不然报错。
  ///fixme table嵌套table实现单元格合并。

  //表格线条颜色
  static Color _BorderColor = Colors.black12;

  //表格线条宽度
  static double _width = 1;

  ///背景色表格标题
  static Color _backgroundColorWithTableTitle = Colors.black12;
  static Color _backgroundColorWithWhite = Colors.white;
  static Color _backgroundColorWithGrey = ColorUtils.parseColor("#F7F6F3");
  static StateSetter? _setState = null;

  static Widget _table(
      BuildContext context, ModifyContractRoyaltyRateBean? data) {
    if (data?.MerchandiserRoyalty == null ||
        data!.MerchandiserRoyalty!.length <= 0) {
      return LibUi.getEmptyView();
    }
    //fixme 表格
    //可以水平滑动的表格
    var scrolltable = _scrolltable(context, data?.MerchandiserRoyalty);
    //水平滑动效果
    var singleChildScrollView = SingleChildScrollView(
        child: scrolltable, scrollDirection: Axis.horizontal);
    return Center(
      child: Container(
        child: singleChildScrollView,
        //width: 2400,
      ),
    );
  }

  ///水平滑动表格
  static Widget _scrolltable(
      BuildContext context, List<MerchandiserRoyaltyBaen>? mDatas) {
    if (mDatas == null || mDatas.length <= 0) {
      return AppUi.getEmptyView();
    }
    var children = <TableRow>[];
    //第一行标题栏
    List<Widget> titleChildren = [];
    titleChildren.add(_text(AppStrings.of(context).TheSerial)); //序号
    titleChildren.add(_text(AppStrings.of(context).TheName)); //姓名
    titleChildren.add(_text(AppStrings.of(context).payrate_)); //提成比例
    titleChildren.add(_text(AppStrings.of(context).Operation)); //操作
    var tableRow = TableRow(
        decoration: BoxDecoration(color: _backgroundColorWithTableTitle),
        children: titleChildren);
    children.add(tableRow);
    //第二行，内容行。
    for (int i = 0; i < mDatas!.length; i++) {
      var mData = mDatas[i];
      List<Widget> rowChildren = [];
      //序号
      var TheSerial = _text("${i + 1}");
      rowChildren.add(TheSerial);
      //姓名
      var TheName = _materialButton(mData?.PersonName ?? "", onPressed: () {
        UserModel.getManagergetlistWith02(context, true, (value) {
          if (value.isSuccessForCode()) {
            var datas = <RollerBean>[];
            value?.Data?.forEach((element) {
              datas.add(
                  RollerBean(key: element.PersonId, value: element.PersonName));
            });
            AppDialog.showDialogWithRollerPicker(context,
                    datas: datas, value: mData?.PersonName)
                ?.then((value) {
              if (value != null && value!.value != null) {
                if (mData.PersonId != value.key) {
                  MerchandiserRoyaltyBaen? delData = null;
                  mDatas?.forEach((element) {
                    if (element.PersonId == value.key) {
                      delData = element;
                    }
                  });
                  if (delData != null) {
                    mDatas?.remove(delData); //移除掉重复的。(把之前旧的移除掉，以现在最新的为准)
                  }
                }
                _setState?.call(() {
                  mData?.PersonId = value.key;
                  mData?.PersonName = value.value;
                });
              }
            });
          } else {
            AppDialog.showDialogWithInfo(context, content: value?.MsgDetail);
          }
        });
      });
      rowChildren.add(TheName);
      //提成比例
      var Ratio = UiBase.itemWithSigleEdit(context, mData?.Ratio,
          isAllowEmpty: true,
          isDecimal: true,
          isNegative: false,
          unit: "%",
          isLine: true, onChanged: (value) {
        if (StringUtils.isEmpty(value)) {
          mData?.Ratio = "0"; //不能为空，为空，提交接口会报数据格式错误。
        } else {
          mData?.Ratio = value;
        }
      },
          focusNode: FocusNodeManager.getFocusNode("${mData?.PersonName}")
              .addListener((value) {
            if (!value) {
              //失去焦点;页面刷新。
              _setState?.call(() {
                if (StringUtils.isEmpty(mData?.Ratio)) {
                  mDatas?.remove(mData); //自动移除；
                } else {
                  try {
                    var d = double.parse(mData!.Ratio);
                    if (d <= 0.0) {
                      mDatas?.remove(mData); //自动移除；
                    }
                  } catch (e) {}
                }
              });
            }
          }));
      rowChildren.add(Ratio);
      var Operation =
          _materialButton(AppStrings.of(context).delete, onPressed: () {
        //删除
        _setState?.call(() {
          mDatas?.removeAt(i);
        });
      });
      rowChildren.add(Operation);
      var tableRow = TableRow(
          // decoration: BoxDecoration(color: _getColor(_index + 1)),
          decoration: BoxDecoration(color: _getColor(i)),
          children: rowChildren);
      children.add(tableRow);
    }
    var table = Table(
      border: TableBorder.all(
          color: _BorderColor, width: _width, style: BorderStyle.solid),
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
      columnWidths: {
        0: IntrinsicColumnWidth(),
        1: IntrinsicColumnWidth(),
        2: IntrinsicColumnWidth(),
        3: IntrinsicColumnWidth(),
        4: IntrinsicColumnWidth(),
        5: IntrinsicColumnWidth(),
        6: IntrinsicColumnWidth(),
        7: IntrinsicColumnWidth(),
        8: IntrinsicColumnWidth(),
        9: IntrinsicColumnWidth(),
        10: IntrinsicColumnWidth(),
        11: IntrinsicColumnWidth(),
        12: IntrinsicColumnWidth(),
        13: IntrinsicColumnWidth(),
        14: IntrinsicColumnWidth(),
        15: IntrinsicColumnWidth(),
        16: IntrinsicColumnWidth(),
        17: IntrinsicColumnWidth(),
        18: IntrinsicColumnWidth(),
        19: IntrinsicColumnWidth(),
      },
      children: children,
    );
    return table;
  }

  //fixme 条目颜色背景
  static Color _getColor(int i) {
    Color _color = _backgroundColorWithWhite;
    //print("=============$i ${i%2}");
    if (i % 2 == 0) {
      _color = _backgroundColorWithGrey;
    }
    return _color;
  }

  //文本
  static Widget _text(String? text, {bool isStart = false}) {
    // return Center(
    //   child: Text(text ?? ""),
    // );
    Widget child;
    if (isStart) {
      var textKey = Text(
        text ?? "",
        style: AppStyle.textStyleWithCard(),
      );
      var value = "*";
      var startText = Text(
        value,
        softWrap: true,
        style: AppStyle.textStyleWithCardRed(),
      );
      child = SizedBox(
        child: Row(
          children: [textKey, startText],
          mainAxisAlignment: MainAxisAlignment.center,
        ),
        width: 120,
      );
    } else {
      child = Text(text ?? "");
    }
    return Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(
          minHeight: 36.0, //最小高度
        ),
        child: Center(
          child: child,
        ),
      ),
    );
  }

  ///按钮
  static Widget _materialButton(String text,
      {VoidCallback? onPressed,
      double radius = 5,
      double height = 35,
      double width = 50,
      Color color = Colors.blueAccent,
      Color textColor = Colors.white,
      double fontSize = 14,
      EdgeInsetsGeometry margin = const EdgeInsets.only(left: 8, right: 8),
      EdgeInsetsGeometry padding =
          const EdgeInsets.only(left: 16, right: 16)}) {
    return Container(
      margin: margin,
      child: MaterialButton(
        padding: padding,
        height: height,
        minWidth: width,
        onPressed: () {
          onPressed?.call();
        },
        //label 右边控件（一般为文本），不能为空
        color: color,
        //color 按钮颜色
        splashColor: Colors.black12,
        //splashColor 点击时，飞溅扩散的颜色
        //highlightColor: Colors.red, //highlightColor 点击时按钮颜色
        colorBrightness: Brightness.light,
        //colorBrightness 按钮亮度；Brightness.dark 暗系风格;Brightness.light 高亮(默认)
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(radius))),
        //shape 形状
        textColor: Colors.white,
        //文本默认颜色
        child: Text(
          text,
          style: TextStyle(
            color: textColor,
            fontSize: fontSize,
          ),
        ), //fixme 子控件
      ),
    );
  }
}
